package com.hubu.admin.service.impl;

import com.hubu.admin.entity.SecurityUser;
import com.hubu.admin.entity.User;
import com.hubu.admin.mapper.UserMapper;
import com.hubu.admin.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hubu.admin.utils.JwtUtils;
import com.hubu.admin.utils.RedisCache;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wx:zjj33126135
 * @since 2023-12-12
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private JwtUtils jwtUtils;

    @Resource
    private RedisCache redisCache;

    @Override
    public Map<String, String> login(String username, String password) {

        //
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if(!authenticate.isAuthenticated()){
            throw new UsernameNotFoundException("请重新检查用户名和密码");
        }

        SecurityUser securityUser = (SecurityUser) authenticate.getPrincipal();

        String userId = securityUser.getUser().getUserId().toString();

        String token = jwtUtils.createJWT(userId);

        Map<String, String> map = new HashMap<>();
        map.put("token",token);

        redisCache.setCacheObject("login"+userId,securityUser);
        return map;
    }
}
